//
//  DetailViewController.swift
//  todoApp
//
//  Created by lili on 15/2/4.
//  Copyright (c) 2015年 ll studio. All rights reserved.
//

import UIKit

class DetailViewController: UIViewController, UIActionSheetDelegate,UITextViewDelegate,PopupViewDelegate {

    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet var noteTag: UITextField!=UITextField()
    @IBOutlet var notesText: UITextView!=UITextView()
    @IBOutlet weak var placeHolder: UILabel!
    var isPresent:Bool?
    var noteId : String?
    var note : NoteModel?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //颜色
        notesText.backgroundColor=BACKGROUND_COLOR
        self.view.backgroundColor=BACKGROUND_COLOR
        
        note = NoteDBManger.shareInstance().queryNoteWithId(noteId)
        self.title = note?.noteText
        notesText.contentInset = UIEdgeInsetsMake(-10, -5, 0, 0);
//        notesText.backgroundColor = UIColor.redColor()
        placeHolder.enabled=false
        notesText.delegate=self
        noteTag.text = note?.noteTag
        notesText.text = note?.noteText
        
        if  (note!.localCreateTime > 0)
        {
            
            timeLabel.text = self.getCreateTimeElapse(note!.localCreateTime) as String
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func donePressed(sender: UIBarButtonItem) {
        
        if let text:NSString = notesText.text
        {
            var tagStr : NSString = noteTag.text!
            
            if  text.isEqualToString(note!.noteText) && tagStr.isEqualToString(note!.noteTag)
            {
                if(isPresent == true)
                {
                    self.dismissViewControllerAnimated(true, completion: nil)
                    return
                }
                self.navigationController?.popToRootViewControllerAnimated(true)
            }
            else
            {
                note?.noteText = text as String
                note?.noteTag = noteTag.text
                
                if  NoteDBManger.shareInstance().updateNote(note!) == false
                {
                    self.showHudWithTitle("更新失败")
                }
                else
                {
                    
                    if (NSUserDefaults.standardUserDefaults().boolForKey("isUserLoggedIn") == true)
                        
                    {
                        var avosQuery = AVQuery(className: "NoteClass")
                        avosQuery.whereKey("userId", equalTo:note?.userId)
                        avosQuery.whereKey("noteId", equalTo: note?.noteId)
                        
                        var results :[AVObject]! = avosQuery.findObjects() as! [AVObject]!
                        
                        if results.count > 0
                        {
                            var avosObj = results[0] as AVObject
                            var uploadArr : NSArray = NSArray(object: NSDictionary(objects: [avosObj,note!], forKeys: ["avosObj","noteObj"]))
                            self.startUploadData(0, uploadArray:uploadArr)
                            
                        }
                        else
                        {
                            var newNoteObj = AVObject(className: "NoteClass")
                            var arr : NSArray = NSArray(object: NSDictionary(objects: [newNoteObj,note!], forKeys: ["avosObj","noteObj"]))
                            self.startUploadData(0, uploadArray: arr)
                        }
                    }
                }
                if(isPresent == true)
                {
                    self.dismissViewControllerAnimated(true, completion: nil)
                    return
                }
                self.navigationController?.popToRootViewControllerAnimated(true)

            }
        }
        
        else
        {
            self.showHudWithTitle("请输入内容")
        }
    }
    
    @IBAction func deletePressed(sender: UIButton) {
        UIAlertView.showWithTitle("删除此条备忘录？", message:"", cancelButtonTitle: "确认", otherButtonTitles: ["取消"], tapBlock: { (alert, idx) -> Void in
            if (idx == 0)
            {
                NoteDBManger.shareInstance().deleleNotes([self.note!])
                let query:AVQuery = AVQuery(className: "NoteClass")
                query.whereKey("userId", equalTo: self.note?.userId)
                query.whereKey("localCreateTime", equalTo: self.note?.localCreateTime)
                query.deleteAllInBackgroundWithBlock(nil)
                self.navigationController?.popToRootViewControllerAnimated(true)
            }
        })
        
    }
    
    @IBAction func sharePressed(sender: UIButton) {
        //在这里添加微信分享代码
        
        var content = notesText.text
        var tagContent = noteTag.text
        
        if( content.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 0)
        {
            self.showHudWithTitle("没有分享内容")
            return;
        }
        
        
//        var popView:Popwindow = Popwindow(frame: self.view.bounds, data: ["分享备忘","分享到朋友圈","分享给微信好友","分享到新浪微博","取消"], uid: -1)
        var popView:Popwindow = Popwindow(frame: self.view.bounds, data: ["分享备忘","分享到朋友圈","分享给微信好友","取消"], uid: -1)
        popView.delegate = self
        self.view.addSubview(popView)
//        var actionSheet = UIActionSheet(title: "分享备忘", delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: "分享到朋友圈", otherButtonTitles: "分享给微信好友")
//        
//        actionSheet.actionSheetStyle = UIActionSheetStyle.BlackOpaque
//        
//        
//        actionSheet.showInView(self.view)
        
    }
    
    func PopupDelegate(title: String!, uid: Int) {
        
        var type:ShareType
        
        if (title == "分享到朋友圈") {
            type = ShareTypeWeixiTimeline
            
        }else if (title == "分享给微信好友")
        {
            type = ShareTypeWeixiSession
            
        }else if(title == "分享到新浪微博")
        {
//            var accessToken:NSString? = NSUserDefaults.standardUserDefaults().objectForKey("accessToken")?.stringValue
//            if (accessToken == nil){
//                var request:WBAuthorizeRequest = WBAuthorizeRequest()
//                request.redirectURI = "https://api.weibo.com/oauth2/default.html"
//                request.scope = "all"
////                request.userInfo = ["SSO_From": "111",
////                    "Other_Info_1":123]
//                WeiboSDK.sendRequest(request)
//            }else
//            {
//                WBHttpRequest(accessToken:accessToken as! String, url: "https://api.weibo.com/2/statuses/update.json", httpMethod: "POST", params: ["status":notesText.text], delegate: self, withTag:"100")
//            }
//            return;
            type = ShareTypeSinaWeibo;
            
        }else
        {
            return;
        }
        
//        var publishContent:ISSContent = ShareSDK.content(nil, defaultContent: nil, image:ShareSDK.pngImageWithImage(UIImage(named: "wechat")), title:notesText.text, url:"www.baidu.com", description: nil, mediaType: SSPublishContentMediaTypeNews)
        
        var publishContent:ISSContent = ShareSDK.content(notesText.text, defaultContent: nil, image:ShareSDK.pngImageWithImage(UIImage(named: "wechat")), title:"标签:" + noteTag.text!, url:"www.baidu.com", description: nil, mediaType: SSPublishContentMediaTypeText)
        
        ShareSDK.shareContent(publishContent, type: type, authOptions: nil, statusBarTips: true) { (share_type:ShareType,state:SSResponseState,statusInfo:ISSPlatformShareInfo!,error:ICMErrorInfo!,end:Bool) -> Void in
            if (state == SSResponseStateSuccess){
                if (share_type == ShareTypeWeixiTimeline || share_type == ShareTypeSinaWeibo)
                {
                    UIAlertView.showWithTitle("分享成功", message:"", cancelButtonTitle: "确定", otherButtonTitles: nil, tapBlock: nil)
                }
                
            }
            else if (state == SSResponseStateFail) {
                
            }
        }

    }
    
    func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
        
        var type:ShareType
        if (buttonIndex == 1)
        {
            return
        }else if(buttonIndex == 0)
        {
            type = ShareTypeWeixiTimeline
        }else
        {
            type = ShareTypeWeixiSession
        }
        
        
        var publishContent:ISSContent = ShareSDK.content(notesText.text, defaultContent: nil, image:ShareSDK.pngImageWithImage(UIImage(named: "wechat")), title:noteTag.text, url:"www.baidu.com", description: nil, mediaType: SSPublishContentMediaTypeNews)
        
        ShareSDK.shareContent(publishContent, type: type, authOptions: nil, statusBarTips: true) { (type:ShareType,state:SSResponseState,statusInfo:ISSPlatformShareInfo!,error:ICMErrorInfo!,end:Bool) -> Void in
            if (state == SSResponseStateSuccess){
                print("分享成功")
            }
            else if (state == SSResponseStateFail) {
                
                }
        }
        
//        var req = SendMessageToWXReq()
//        req.text = notesText.text.stringByAppendingString(noteTag.text)
//        req.bText = true
//        if(buttonIndex == 0)
//        {
//            req.scene = 1
//        }
//        else
//        {
//            req.scene = 0
//        }
//        
//        var ret =  WXApi.sendReq(req)
        
        return
    }


    /*func textViewDidChange(notesText: UITextView) {
        if notesText.text.isEmpty {
            
        placeHolder.text="请输入正文"
            
        }
        else
        {
        placeHolder.text=" "
        }
    }
*/
    func textViewDidBeginEditing(textView: UITextView) {
        placeHolder.text=" "
    }
}

